package com.code9xs.util;

import com.aliyun.dysmsapi20170525.*;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.tea.*;
import com.aliyun.teaopenapi.*;
import com.aliyun.teaopenapi.models.*;

import java.util.Random;


public class CheckCodeUtil {

    private static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static String getCheckCode() {
        Random random = new Random();
        String result="";
        for (int i=0;i<6;i++)
        {
            result+=random.nextInt(10);
        }
            return result;
    }

    public static String sendMessage(String phoneNumber,String checkCode){
        String statusCode = null;
        try {
            Client client = createClient("", "");
            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            sendSmsRequest.phoneNumbers = phoneNumber;
            // 短信签名名称
            sendSmsRequest.signName = "";
            // 短信模板ID
            sendSmsRequest.templateCode = "";
            // 验证码，需要JSON格式
            sendSmsRequest.templateParam = "'code':'" + checkCode + "'";
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            // 返回请求状态码，返回OK代表请求成功。
            statusCode =  sendSmsResponse.body.code;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusCode;
    }

    // 将验证码上传至redis，设置过期时间为6分钟，用户id为键，验证码为值
    public static boolean checkCodeRedis(){
        return false;
    }

    public static String verifyCheckCode(String key,String checkCode){
        // 从redis取出用户验证码
        String trueCheckCode = "";
        if (trueCheckCode == null || trueCheckCode == "" || trueCheckCode == "null"){
            return "验证码已过期";
        }
        if (checkCode.equals(trueCheckCode)){
            return "验证码正确";
        } else {
            return "验证码错误";
        }
    }
}